package com.tencent.qplus.paddata.stat;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tencent.qplus.paddata.db.DataSourceManager;
import com.tencent.qplus.paddata.util.JdbcUtils;

public class DbOptThread extends Thread {
	private Connection conn;
	private PreparedStatement loginPst;
	private PreparedStatement userinfoPst;
	private Logger logger = Logger.getLogger(DbOptThread.class);
	private List<LogData> list = new ArrayList<LogData>();
	private int tableIndex;
	
	public DbOptThread(int tableIndex){
		this.tableIndex = tableIndex;
	}
	
	public void add(LogData data) throws SQLException{
		list.add(data);
	}
	
	public void run(){
		logger.info(this.getName()+"  start......");
		try {
			conn = DataSourceManager.getInstance().getDataSource("paddatadb").getConnection();
			String loginSql = "INSERT ignore into uinlogin_"+tableIndex+" (uin,logindate) VALUES(?,?);";
		    String userinfoSql = "INSERT ignore into userinfo_"+tableIndex+"(uin,loginDate,loginType,deviceId,phoneSys,version,romVersion,hasSim)VALUES(?,?,?,?,?,?,?,?)";
		    loginPst = conn.prepareStatement(loginSql);
		    userinfoPst = conn.prepareStatement(userinfoSql);
		    int size = list.size();
		    for(int i=0;i<size;i++){
		    	LogData data = list.get(i);
		    	loginPst.setString(1, data.uin);
		 	    loginPst.setString(2, data.loginDate);
		 	    loginPst.addBatch();
		 	    //"replace into userinfo_"+i+"(uin,loginDate,loginType,deviceId,phoneSys,version,romVersion,hasSim)VALUES(?,?,?,?,?,?,?,?)";
		 	    userinfoPst.setString(1, data.uin);
		 	    userinfoPst.setString(2, data.loginDate);
		 	    userinfoPst.setString(3, data.loginType);
		 	    userinfoPst.setLong(4, data.deviceId);
		 	    userinfoPst.setString(5, data.phoneSys);
		 	    userinfoPst.setString(6, data.version);
		 	    userinfoPst.setString(7, data.romVersion);
		 	    userinfoPst.setString(8, data.hasSim);
		 	    userinfoPst.addBatch();
		 	    if(i>0 && i%1000==0){
		 	    	loginPst.executeBatch();
					userinfoPst.executeBatch();
		 	    }
		    }
		    loginPst.executeBatch();
			userinfoPst.executeBatch();
		} catch (SQLException e) {
			logger.error(e);
		}finally{
			JdbcUtils.release(loginPst);
			JdbcUtils.release(userinfoPst);
			JdbcUtils.release(conn);
		}
		logger.info(this.getName()+"  done......");
	}
}
